package com.shuke.sk_worm.tool.hiskpi.Impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.shuke.sk_worm.consts.ShopPlatformEnum;
import com.shuke.sk_worm.domain.HisKpi;
import com.shuke.sk_worm.domain.SkRealData;
import com.shuke.sk_worm.service.HisKpiService;
import com.shuke.sk_worm.service.SkRealDataService;
import com.shuke.sk_worm.tool.TimeUtil;
import com.shuke.sk_worm.vo.PingduoduoDataVo;
import com.shuke.sk_worm.vo.RealDataVo;
import com.shuke.sk_worm.vo.ShopInfoListVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Component
public class PingduoduoShopImpl extends ShopDataImpl{

    private String dataUrl = "https://mms.pinduoduo.com/chats/csReportDetail?starttime=%d&endtime=%d";

    @Autowired
    private HisKpiService hisKpiService;

    @Autowired
    private SkRealDataService realDataService;

    private List<PingduoduoDataVo> getUrlData(Date date, String cookie, List<String> shopAccounts){
        Long timestamp = date.getTime() / 1000;

        String url = String.format(dataUrl, timestamp, timestamp);

        String data = HttpRequest.get(url).header("Cookie", cookie).execute().body();

        JSONObject result = JSONUtil.parseObj(data);

        JSONObject dataObject = JSONUtil.parseObj(result.get("result"));

        List<PingduoduoDataVo> pingduoduoDatas = JSONUtil.toList(JSONUtil.parseArray(dataObject.get("data")), PingduoduoDataVo.class);

        List<PingduoduoDataVo>  pingduoduoDataVos =  new ArrayList<>();
        pingduoduoDatas.forEach(vo -> {
            if (shopAccounts.contains(vo.getCs_name())){
                pingduoduoDataVos.add(vo);
            }
        });
        return pingduoduoDataVos;
    }

    public List<HisKpi> getHisKpi(ShopInfoListVo shop, List<PingduoduoDataVo> data, Date date){
        if (data.isEmpty()){
            return null;
        }

        Long timestamp = date.getTime();

        SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String terDate = f.format(date);

        List<HisKpi> hisYesterDatas = new ArrayList<>();
        for (PingduoduoDataVo vo : data){
            HisKpi hisYester = new HisKpi();
            hisYester.setStaffName(vo.getCs_name());
            hisYester.setStaffUsername(vo.getCs_name());
            hisYester.setLaborUserAmount(vo.getReceive_user_cnt());
            if (vo.getReply_rate_3_min() != null){
                BigDecimal replyRate = vo.getReply_rate_3_min().multiply(new BigDecimal(100));
                hisYester.setThreeMinResponseConRate(String.valueOf(replyRate));
                hisYester.setThreeMinResponseRate(String.valueOf(replyRate));
            }
            if (vo.getUnsatisfied_serve_score_rate() != null){
                hisYester.setDissatisfactionRate(vo.getUnsatisfied_serve_score_rate());
                hisYester.setSatisfactionRate(TimeUtil.subPercent(vo.getUnsatisfied_serve_score_rate()));
            }
            if (vo.getAvg_reply_time() != null){
                Integer replyTime = (int) Math.ceil(vo.getAvg_reply_time());
                hisYester.setAvgResponseDuration(String.valueOf(replyTime));
            }

            hisYester.setInquirerAmount(vo.getInquiry_user());
            hisYester.setCreateOrderAmount(vo.getFinal_group_user());
            hisYester.setInquiryConversionRate(vo.getInquiry_group_rate());
            if (vo.getCs_sales_amount() != null){
                BigDecimal saleAmount =  new BigDecimal(vo.getCs_sales_amount());
                BigDecimal sale = saleAmount.divide(new BigDecimal(100));
                hisYester.setSalesAmount(String.valueOf(sale));
            }
            hisYester.setInsertTime(terDate);
            hisYester.setInsertTimestamp(timestamp);
            hisYester.setUserId(shop.getUserId());
            hisYester.setUserName(shop.getUserName());
            hisYester.setShopId(shop.getId());
            hisYester.setShopName(shop.getName());
            hisYester.setUserIds(shop.getUserIds());
            hisYester.setDeptId(shop.getDeptId());
            hisYester.setDeptIds(shop.getDeptIds());
            hisYester.setDeptNames(shop.getDeptNames());
            hisYester.setPlatform(ShopPlatformEnum.PINXI);
            hisYester.setBusinessManagerIds(shop.getBusinessManagerIds());
            hisYester.setBusinessManagerNames(shop.getBusinessManagerNames());
            hisYester.setBaseManagerIds(shop.getBaseManagerIds());
            hisYester.setBaseManagerNames(shop.getBaseManagerNames());

            hisYesterDatas.add(hisYester);
        }
        return hisYesterDatas;
    }

    @Override
    public void hiskpi(List<ShopInfoListVo> shopInfoList, Map<Long,String> shopCookie, Date date){
        if (shopInfoList.isEmpty()){
            return;
        }

        for(ShopInfoListVo shop : shopInfoList){
            if (!shopCookie.containsKey(shop.getId())) {
                logger.info("店铺ID :" + shop.getId() + "未获取到Token");
                continue;
            }

            //账号信息
            List<String> shopAccounts = shop.getAccountInfos().stream().map(vo->{
                return  vo.getShopAccount().trim();
            }).collect(Collectors.toList());

            //昨日的数据
            List<PingduoduoDataVo> yesterData = getUrlData(date, shopCookie.get(shop.getId()), shopAccounts);
            if (!yesterData.isEmpty()){
                List<HisKpi> yesterDatas = getHisKpi(shop, yesterData, date);
                hisKpiService.batchInsertData(yesterDatas);
            }

            //24小时前的数据
            Date fourDay = DateUtil.offsetDay(date, -1);
            List<PingduoduoDataVo> fourData =  getUrlData(fourDay, shopCookie.get(shop.getId()), shopAccounts);
            if (!fourData.isEmpty()){
                List<HisKpi> fourDatas = getHisKpi(shop, fourData, fourDay);
                //保存数据
                hisKpiService.batchInsertData(fourDatas);
            }

            Date eightDay = DateUtil.offsetDay(fourDay, -1);
            List<PingduoduoDataVo> eightData = getUrlData(eightDay, shopCookie.get(shop.getId()), shopAccounts);
            if (!eightData.isEmpty()){
                List<HisKpi> eightDatas = getHisKpi(shop, eightData, eightDay);
                //保存数据
                hisKpiService.batchInsertData(eightDatas);
            }
        }
    }

    @Override
    public void realData(List<ShopInfoListVo> shopInfoList, Map<Long,String> shopCookie){
        if (shopInfoList.isEmpty()){
            return;
        }

        for (ShopInfoListVo shop : shopInfoList) {
            logger.info("Real_DATA: 店铺：" + shop.getName());
            Long nowTimeMillis = System.currentTimeMillis();  //时间戳

            SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd");
            //将时间转换指定格式的日期
            String nowDate = f.format(nowTimeMillis);

            if (!shopCookie.containsKey(shop.getId())) {
                logger.info("店铺ID :" + shop.getId() + "未获取到Token");
                continue;
            }

            //账号信息
            List<String> shopAccounts = shop.getAccountInfos().stream().map(vo->{
                return  vo.getShopAccount().trim();
            }).collect(Collectors.toList());

            List<PingduoduoDataVo> data = getUrlData(DateUtil.parse(nowDate), shopCookie.get(shop.getId()), shopAccounts);

            List<SkRealData> datas = new ArrayList<>();

            if (!data.isEmpty()){
                data.forEach(real->{
                    SkRealData realData = new SkRealData();

                    realData.setStaffName(real.getCs_name());
                    realData.setStaffUsername(real.getCs_name());
                    realData.setUserId(shop.getUserId());
                    realData.setUserIds(shop.getUserIds());
                    realData.setUserName(shop.getUserName());
                    realData.setShopId(shop.getId());
                    realData.setShopName(shop.getName());
                    realData.setDeptId(shop.getDeptId());
                    realData.setToReplyNum(real.getNeed_manu_reply_consult_user_cnt());
                    realData.setMaxChatNum(String.valueOf(real.getReceive_user_cnt()));
                    realData.setLaborUserAmount(String.valueOf(real.getReceive_user_cnt()));
                    if (real.getAvg_reply_time() != null){
                        Integer replyTime = (int) Math.ceil(real.getAvg_reply_time());
                        realData.setAvgResponseDuration(String.valueOf(replyTime));
                    }

                    if (real.getUnsatisfied_serve_score_rate() != null){
                        realData.setDissatisfactionRate(real.getUnsatisfied_serve_score_rate());
                        realData.setSatisfactionRate(TimeUtil.subPercent(real.getUnsatisfied_serve_score_rate()));
                    }

                    if (real.getReply_rate_3_min() != null){
                        BigDecimal replyRate = real.getReply_rate_3_min().multiply(new BigDecimal(100));
                        realData.setThreeMinResponseConRate(String.valueOf(replyRate));
                        realData.setThreeMinResponseRate(String.valueOf(replyRate));
                    }
                    realData.setInquiryConversionRate(real.getInquiry_group_rate());

                    realData.setInsertTimestamp(nowTimeMillis);
                    realData.setDeptIds(shop.getDeptIds());
                    realData.setDeptNames(shop.getDeptNames());
                    realData.setBusinessManagerIds(shop.getBusinessManagerIds());
                    realData.setBusinessManagerNames(shop.getBusinessManagerNames());
                    realData.setBaseManagerIds(shop.getBaseManagerIds());
                    realData.setPlatform(ShopPlatformEnum.PINXI);
                    realData.setBaseManagerNames(shop.getBaseManagerNames());

                    datas.add(realData);
                });

                if (!realDataService.saveBatch(datas)){
                    logger.info(datas);
                }
            }
        }
    }
}
